package agh.sr.lab4.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class BankAccountDataFileProvider implements IBankAccountDataProvider {
	private static final String BANK_EXT = ".account";

	@Override
	public boolean createAccount(String pesel) throws IOException {
		File file = new File(getPathToAccount(pesel));
		if (!file.exists()) {

			file.createNewFile();
		}

		PrintWriter writer = new PrintWriter(file);
		writer.print("0");
		writer.close();

		return true;
	}

	@Override
	public boolean doesAccountExist(String pesel) {
		return new File(getPathToAccount(pesel)).exists();
	}

	@Override
	public void setNewBalance(String pesel, double amount)
			throws FileNotFoundException {
		PrintWriter writer = new PrintWriter(getPathToAccount(pesel));
		writer.print(amount);
		writer.close();
	}

	@Override
	public double getCurrentBalance(String pesel) throws IOException {
		File file = new File(getPathToAccount(pesel));
		BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
		String line = bufferedReader.readLine();
		bufferedReader.close();
		return Double.parseDouble(line);
	}

	private String getPathToAccount(String pesel) {
		return pesel + BANK_EXT;
	}

	public static void main(String[] args) {
		IBankAccountDataProvider utils = new BankAccountDataFileProvider();
		String pesel = "1234";
		try {
			System.out.println(utils.doesAccountExist(pesel));
			utils.createAccount(pesel);
			System.out.println(utils.doesAccountExist(pesel));
			System.out.println(utils.getCurrentBalance(pesel));
			utils.setNewBalance(pesel, 123);
			System.out.println(utils.getCurrentBalance(pesel));

			double current = utils.getCurrentBalance(pesel);
			double newVal = current - 23;
			utils.setNewBalance(pesel, newVal);
			System.out.println(utils.getCurrentBalance(pesel));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
